/**
 * Notes: 兼职模块业务逻辑
 * Ver : CCMiniCloud Framework 2.0.1 ALL RIGHTS RESERVED BY cclinux0730 (wechat)
 * Date: 2024-03-23 04:00:00 
 */

const BaseProjectService = require('./base_project_service.js');
const dataUtil = require('../../../framework/utils/data_util.js');
const timeUtil = require('../../../framework/utils/time_util.js');
const util = require('../../../framework/utils/util.js');
const cloudUtil = require('../../../framework/cloud/cloud_util.js');
const FoodModel = require('../model/food_model.js');
const UserModel = require('../model/user_model.js');

class FoodService extends BaseProjectService {

	// 获取当前状态
	getStatusDesc(food) {
    let statusMap={
      0:"待处理",
      1:"在处理",
      9:"已完成"
    }
    let statusStr = statusMap[food.FOOD_STATUS]

    if(food.FOOD_STATUS==0&&food.FOOD_END_TIME<this._timestamp){
     statusStr="已过期"
    }
    return statusStr;
	}

	/** 接单 */
	async acceptFood(userId, id) {

    let userName = await UserModel.getOneField({ USER_MINI_OPENID: userId }, 'USER_NAME');
    let updateData={
      FOOD_STATUS:1,
      FOOD_ACCEPT_USER_ID: userId,
      FOOD_ACCEPT_USER_NAME: userName,
      FOOD_ACCEPT_TIME: Date.now(), 
    }
    return await FoodModel.insertOrUpdate({ _id: id },updateData)
	}

	/** 取消我的订单 */
	async cancelFood(userId, id) {
    let updateData={
      FOOD_STATUS:0,
      FOOD_ACCEPT_USER_ID: '',
      FOOD_ACCEPT_USER_NAME: '',
      FOOD_ACCEPT_TIME: 0, 
    }
    return await FoodModel.insertOrUpdate({ _id: id },updateData)
	}

	/** 浏览 */
	async viewFood(id) {
		let fields = '*';

		let where = {
			_id: id,
			//FOOD_STATUS: 1
		}

		let food = await FoodModel.getOne(where, fields);
		if (!food) return null;

		// 接单人信息
		if (food.FOOD_STATUS > 0 && food.FOOD_ACCEPT_USER_ID) {
			food.acceptUser = await UserModel.getOne({ USER_MINI_OPENID: food.FOOD_ACCEPT_USER_ID }, 'USER_NAME,USER_MOBILE');
		}

		FoodModel.inc(id, 'FOOD_VIEW_CNT', 1);

		return food;
	}

	/** 获取 */
	async getFoodDetail(id) {
		return await FoodModel.getOne(id);
	}

	/**修改状态 */
	async statusFood(userId, id, status) {
		    // 构造更新数据
        const updates = {
          FOOF_STATUS: status,
    };
    
    // 执行更新操作
    return await FoodModel.insertOrUpdate({ _id: id },  updates)
	}

	/** 删除 */
	async delFood(userId, id) {
				// 这里可以选择真正的删除或者标记为已删除
        await FoodModel.del({ _id: id });
	
        return true;
	}
  async checkMy(id,userId){
    // 验证邮件是否存在
let follow = await FoodModel.getOne({ _id: id });
if (!follow) {
  throw new Error('邮件不存在');
}

// 检查是否是邮件的创建者或者是有权限修改的人
if (follow.FOOD_USER_ID !== userId) {
  throw new Error('您没有权限编辑此邮件');
}
}
	/** 插入 */
	async insertFood(userId,{cateId,cateName,end,forms,order}) {
		try {
       
      let userName = await UserModel.getOneField({ USER_MINI_OPENID: userId }, 'USER_NAME');
        const data = {
            _pid: this.getProjectId(),
            //FOOD_ID: uniCloud.util.uniqueId(),
            FOOD_STATUS: 0, // 默认状态为待处理
            FOOD_END_TIME: timeUtil.time2Timestamp(end), // 如果需要设置截止时间，可以在后续逻辑中添加
            FOOD_CATE_ID: cateId, // 分类ID，根据实际情况设置
            FOOD_CATE_NAME: cateName, // 分类名称，根据实际情况设置
            FOOD_ORDER: order,
            FOOD_VOUCH: 0,
            FOOD_USER_ID: userId,
            FOOD_USER_NAME: userName, // 假设从 UserModel 中获取用户名
            FOOD_ACCEPT_USER_ID: '',
            FOOD_ACCEPT_USER_NAME: '',
            FOOD_ACCEPT_TIME: 0,
            FOOD_OVER_TIME: 0,
            FOOD_DAY: '', // 日期，如果需要设置日期，可以在后续逻辑中添加
            FOOD_FORMS: forms,
            FOOD_OBJ: dataUtil.dbForms2Obj(forms),
            FOOD_FAV_CNT: 0,
            FOOD_FAV_LIST: [],
            FOOD_VIEW_CNT: 0,
            FOOD_QR: '',
            FOOD_ADD_TIME: Date.now(),
            FOOD_EDIT_TIME: Date.now(),
            FOOD_ADD_IP: '', // IP 地址，可以从客户端获取
            FOOD_EDIT_IP: '' // IP 地址，可以从客户端获取
        };
  
        // 插入数据
        let id = await FoodModel.insert(data);
		return await FoodModel.getOne(id);
    } catch (error) {
        console.error('[插入邮件时发生错误]', error);
        throw new Error('插入邮件时出现问题，请稍后再试或联系支持人员');
    }
	}

	/** 修改 */
	async editFood(userId,{id,cateId,cateName,end,forms,order}) {

    try {
      //this.checkMy(id,userId)

			// 构造更新数据
       const updates = {
	           FOOD_END_TIME: timeUtil.time2Timestamp(end),
	           FOOD_CATE_ID: cateId,
	           FOOD_CATE_NAME: cateName,
	           FOOD_ORDER: order,
	           FOOD_FORMS: forms,
	           FOOD_OBJ: dataUtil.dbForms2Obj(forms),
	           FOOD_EDIT_TIME: Date.now(),
	           FOOD_EDIT_IP: '' // IP 地址，可以从客户端获取
	    };
	
			// 执行更新操作
			await FoodModel.insertOrUpdate({ _id: id },  updates
	);
	
			// 返回更新后的邮件信息
			return await FoodModel.getOne(id);
		} catch (error) {
			console.error('[编辑时发生错误]', error);
			throw new Error('编辑时出现问题，请稍后再试或联系支持人员');
		}
	}

	/** 更新forms信息 */
	async updateFoodForms({
		id,
		hasImageForms
	}) {
		return await MailModel.editForms({_id:id},"FOOD_FORMS","FOOD_OBJ",hasImageForms,util.getProjectId());	}

	/** 列表与搜索 */
	async getFoodList(userId, {
		search, // 搜索条件
		sortType, // 搜索菜单
		sortVal, // 搜索菜单
		orderBy, // 排序
		whereEx, //附加查询条件
		page,
		size,
		isTotal = true,
		oldTotal }) {
		orderBy = orderBy || {
			'FOOD_ORDER': 'asc',
			'FOOD_ADD_TIME': 'desc'
		};
		let fields = 'FOOD_ACCEPT_USER_ID,FOOD_END_TIME,FOOD_STATUS,FOOD_ADD_TIME,FOOD_USER_ID,FOOD_OBJ';

		let where = {};
		where.and = {
			//FOOD_STATUS: 1,
			_pid: this.getProjectId() //复杂的查询在此处标注PID
		};


		if (util.isDefined(search) && search) {
			if (search == '我的发布') {
				where.and.FOOD_USER_ID = userId;
			}
			else if (search == '我的接单') {
				where.and.FOOD_ACCEPT_USER_ID = userId;
			}
			else if (search == '我的收藏') {
				where.and.FOOD_FAV_LIST = userId;
			}

			else {
				where.or = [
					{ 'FOOD_OBJ.title': ['like', search] },
					{ 'FOOD_OBJ.poster': ['like', search] },
					{ 'FOOD_OBJ.tel': ['like', search] },
				];
			}

		} else if (sortType && util.isDefined(sortVal)) {
			// 搜索菜单
			switch (sortType) {
				case 'cateId': {
					where.and.FOOD_CATE_ID = String(sortVal);
					break;
				}
				case 'status': {
					where.and.FOOD_STATUS = Number(sortVal);
					break;
				}
				case 'timeout': { //过期
					where.and.FOOD_STATUS = 0;
					where.and.FOOD_END_TIME = ['<', this._timestamp]
					break;
				}
				case 'wait': { //待接单
					where.and.FOOD_STATUS = 0;
					where.and.FOOD_END_TIME = ['>=', this._timestamp]
					break;
				}
				case 'sort': {
					orderBy = this.fmtOrderBySort(sortVal, 'FOOD_ADD_TIME');
					break;
				}
			}
		}

		return await FoodModel.getList(where, fields, orderBy, page, size, isTotal, oldTotal);

	}

}

module.exports = FoodService;